# -*- coding: utf-8 -*-
"""
Created on Sun Sep 21 05:29:01 2025

@author: surpass

学生管理类定义
"""

from models.student import Student

class StudentManager:
    """学生管理类，负责管理学生集合和操作"""
    
    def __init__(self):
        self.students = []  # 存储Student对象的列表
    
    def add_student(self, student):
        """添加学生"""
        self.students.append(student)
        print(f"成功添加学生: {student.name} (学号: {student.student_id})")
    
    def add_student_from_input(self):
        """从用户输入添加学生"""
        try:
            student = Student.from_input()
            self.add_student(student)
            return True
        except ValueError:
            print("输入错误！成绩必须是数字，请重新输入。")
            return False
        except KeyboardInterrupt:
            print("\n操作已取消")
            return False
    
    def show_all_students(self):
        """显示所有学生信息"""
        print("\n--- 所有学生信息 ---")
        if not self.students:
            print("暂无学生信息！")
            return
        
        # 打印表头
        header = f"{'序号':<4} {'学号':<12} {'姓名':<8} {'班级':<6} "
        # 实验成绩
        for i in range(1, 9):
            header += f"{'实验'+str(i):<6}"
        # 作业成绩
        for i in range(1, 9):
            header += f"{'作业'+str(i):<6}"
        # 在线学习和总成绩
        header += f"{'在线70%':<8} {'在线20%':<8} {'在线10%':<8} {'平时总合':<8} {'期末':<6} {'总评':<6}"
        
        print(header)
        print("-" * 150)
        
        # 打印每个学生的信息
        for i, student in enumerate(self.students, 1):
            print(f"{i:<4} {student.display_info()}")
    
    def search_students(self, keyword):
        """搜索学生信息"""
        found = [s for s in self.students if keyword in s.student_id or keyword in s.name]
        return found
    
    def display_search_results(self, found_students):
        """显示搜索结果"""
        if not found_students:
            print("未找到相关学生！")
            return
        
        # 打印表头
        header = f"{'学号':<12} {'姓名':<8} {'班级':<6} "
        # 实验成绩
        for i in range(1, 9):
            header += f"{'实验'+str(i):<6}"
        # 作业成绩
        for i in range(1, 9):
            header += f"{'作业'+str(i):<6}"
        # 在线学习和总成绩
        header += f"{'在线70%':<8} {'在线20%':<8} {'在线10%':<8} {'平时总合':<8} {'期末':<6} {'总评':<6}"
        
        print(header)
        print("-" * 150)
        
        for student in found_students:
            print(student.display_info())
    
    def delete_student(self, index):
        """删除学生"""
        if 0 <= index < len(self.students):
            deleted = self.students.pop(index)
            print(f"已删除学生: {deleted.name} (学号: {deleted.student_id})")
            return True
        else:
            print("无效的序号！")
            return False
    
    def calculate_statistics(self):
        """计算成绩统计"""
        print("\n--- 成绩统计 ---")
        if not self.students:
            print("暂无学生信息！")
            return
        
        # 计算实验平均分
        exp_avgs = []
        for i in range(8):
            total = sum(student.experiments[i] for student in self.students)
            exp_avgs.append(total / len(self.students))
        
        # 计算作业平均分
        hw_avgs = []
        for i in range(8):
            total = sum(student.homeworks[i] for student in self.students)
            hw_avgs.append(total / len(self.students))
        
        # 计算其他项目的平均分
        online_70_avg = sum(student.online_learning_70 for student in self.students) / len(self.students)
        online_20_avg = sum(student.online_learning_20 for student in self.students) / len(self.students)
        online_10_avg = sum(student.online_learning_10 for student in self.students) / len(self.students)
        usual_avg = sum(student.usual_total for student in self.students) / len(self.students)
        final_avg = sum(student.final_exam for student in self.students) / len(self.students)
        total_avg = sum(student.total_score for student in self.students) / len(self.students)
        
        # 打印实验平均分
        print("实验平均分:")
        for i, avg in enumerate(exp_avgs, 1):
            print(f"实验{i}: {avg:.2f}")
        
        # 打印作业平均分
        print("\n作业平均分:")
        for i, avg in enumerate(hw_avgs, 1):
            print(f"作业{i}: {avg:.2f}")
        
        # 打印其他平均分
        print(f"\n在线学习(70%)平均分: {online_70_avg:.2f}")
        print(f"在线学习(20%)平均分: {online_20_avg:.2f}")
        print(f"在线学习(10%)平均分: {online_10_avg:.2f}")
        print(f"平时总合平均分: {usual_avg:.2f}")
        print(f"期末平均分: {final_avg:.2f}")
        print(f"总评平均分: {total_avg:.2f}")